//
//  AddFriendsViewController.m
//  觅影
//
//  Created by  陶虹 on 16/4/9.
//  Copyright © 2016年  陶虹. All rights reserved.
//

#import "AddFriendsViewController.h"
#import "AddFriendsItem.h"
#import "RecommendFriendsModel.h"
#import "RecommendHeaderView.h"
#import "SearchFriendsModel.h"
#import "MyFriendsCell.h"
#import "PersonInfoViewController.h"

#define Kspace (KWIDTH - 280) / 8

@interface AddFriendsViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate>
@property (strong, nonatomic) IBOutlet UITextField *textField;
@property (strong, nonatomic) IBOutlet UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *modelArray;
@property (nonatomic, strong) NSMutableArray *searchedFriendsArray;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, assign) NSInteger startIndex;

@end


@implementation AddFriendsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"添加好友";
    [self putUpView];
    [self netRequest];
    
}


- (NSMutableArray *)modelArray{
    if (!_modelArray) {
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}

// 推荐好友 熊掌网络请求

- (void)netRequest{
    
    NSURLSessionConfiguration* sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    /* Create session, and optionally set a NSURLSessionDelegate. */
    NSURLSession* session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:nil delegateQueue:nil];
    
    /* Create the Request:
     My API (GET http://static.v6v7.com/snowman_api/user/recommend_user_list)
     */
    
    NSURL* URL = [NSURL URLWithString:@"http://static.v6v7.com/snowman_api/user/recommend_user_list"];
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
    request.HTTPMethod = @"GET";
    
    // Headers
    
    [request addValue:@"sessionid=glgiv8grxi44vfanrzk3ff53rg44sdfr" forHTTPHeaderField:@"Cookie"];
//    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    // JSON Body
    
//    NSDictionary* bodyObject = @{
    
//                                 };
//    request.HTTPBody = [NSJSONSerialization dataWithJSONObject:bodyObject options:kNilOptions error:NULL];
    
    /* Start a new Task */
    NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error == nil) {
            // Success
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *resultArray = dic[@"result"];
            for (NSDictionary *resultDic in resultArray) {
                RecommendFriendsModel *model = [[RecommendFriendsModel alloc] init];
                [model setValuesForKeysWithDictionary:resultDic];
                [self.modelArray addObject:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.collectionView reloadData];
            });
        }
        else {
            // Failure
            NSLog(@"添加好友界面请求数据失败");
        }
    }];
    [task resume];
}

- (void)putUpView{
    self.startIndex = 1;
    self.edgesForExtendedLayout = NO;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerNib:[UINib nibWithNibName:@"AddFriendsItem" bundle:nil] forCellWithReuseIdentifier:@"addFriendsItem"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"RecommendHeaderView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"recommendHeaderView"];
    
    self.textField.delegate = self;
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 50;
    self.tableView.hidden = YES;
    [self.tableView registerNib:[UINib nibWithNibName:@"MyFriendsCell" bundle:nil] forCellReuseIdentifier:@"myFriendsCell"];
    self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        [self searchNetRequestMore];
    }];

}
- (NSMutableArray *)searchedFriendsArray{
    if (!_searchedFriendsArray) {
        self.searchedFriendsArray = [NSMutableArray array];
    }
    return _searchedFriendsArray;
}
// 搜索好友网络请求
- (void)searchNetRequest{
    // 转码
//    NSString *nickname = [self.textField.text stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    
    NSURLSessionConfiguration* sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    /* Create session, and optionally set a NSURLSessionDelegate. */
    NSURLSession* session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:nil delegateQueue:nil];
    
    /* Create the Request:
     My API (GET http://static.v6v7.com/snowman_api/user/search_nickname)
     */
    
    NSURL* URL = [NSURL URLWithString:@"http://static.v6v7.com/snowman_api/user/search_nickname"];
    NSDictionary* URLParams = @{
                                @"nickname": self.textField.text,
                                @"page": @"1",
                                @"page_size": @"10",
                                };
    URL = NSURLByAppendingQueryParameters(URL, URLParams);
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
    request.HTTPMethod = @"GET";
    
    // Headers
    
    [request addValue:@"sessionid=glgiv8grxi44vfanrzk3ff53rg44sdfr" forHTTPHeaderField:@"Cookie"];
//    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    // JSON Body
    
//    NSDictionary* bodyObject = @{
    
//                                 };
//    request.HTTPBody = [NSJSONSerialization dataWithJSONObject:bodyObject options:kNilOptions error:NULL];
    
    /* Start a new Task */
    NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error == nil) {
            // Success
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *dataArray = dic[@"result"][@"data"];
            for (NSDictionary *dataDic in dataArray) {
                SearchFriendsModel *model = [[SearchFriendsModel alloc] init];
                [model setValuesForKeysWithDictionary:dataDic];
                [self.searchedFriendsArray addObject:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        }
        else {
            // Failure
            NSLog(@"搜索好友网络请求失败");
        }
    }];
    [task resume];
}
#pragma mark --- 搜索好友列表上拉加载 ---
- (void)searchNetRequestMore{
    self.startIndex ++;
    NSURLSessionConfiguration* sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    /* Create session, and optionally set a NSURLSessionDelegate. */
    NSURLSession* session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:nil delegateQueue:nil];
    
    /* Create the Request:
     My API (GET http://static.v6v7.com/snowman_api/user/search_nickname)
     */
    
    NSURL* URL = [NSURL URLWithString:@"http://static.v6v7.com/snowman_api/user/search_nickname"];
    NSDictionary* URLParams = @{
                                @"nickname": self.textField.text,
                                @"page": [NSString stringWithFormat:@"%ld",self.startIndex],
                                @"page_size": @"10",
                                };
    URL = NSURLByAppendingQueryParameters(URL, URLParams);
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
    request.HTTPMethod = @"GET";
    
    // Headers
    
    [request addValue:@"sessionid=glgiv8grxi44vfanrzk3ff53rg44sdfr" forHTTPHeaderField:@"Cookie"];
    //    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    // JSON Body
    
    //    NSDictionary* bodyObject = @{
    
    //                                 };
    //    request.HTTPBody = [NSJSONSerialization dataWithJSONObject:bodyObject options:kNilOptions error:NULL];
    
    /* Start a new Task */
    NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error == nil) {
            // Success
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *dataArray = dic[@"result"][@"data"];
            for (NSDictionary *dataDic in dataArray) {
                SearchFriendsModel *model = [[SearchFriendsModel alloc] init];
                [model setValuesForKeysWithDictionary:dataDic];
                [self.searchedFriendsArray addObject:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
                [self.tableView.mj_footer endRefreshing];
            });
        }
        else {
            // Failure
            NSLog(@"搜索好友网络请求失败");
        }
    }];
    [task resume];
}

static NSString* NSStringFromQueryParameters(NSDictionary* queryParameters)
{
    NSMutableArray* parts = [NSMutableArray array];
    [queryParameters enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
        NSString *part = [NSString stringWithFormat: @"%@=%@",
                          [key stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]],
                          [value stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]
                          ];
        [parts addObject:part];
    }];
    return [parts componentsJoinedByString: @"&"];
}

/**
 Creates a new URL by adding the given query parameters.
 @param URL The input URL.
 @param queryParameters The query parameter dictionary to add.
 @return A new NSURL.
 */
static NSURL* NSURLByAppendingQueryParameters(NSURL* URL, NSDictionary* queryParameters)
{
    NSString* URLString = [NSString stringWithFormat:@"%@?%@",
                           [URL absoluteString],
                           NSStringFromQueryParameters(queryParameters)
                           ];
    return [NSURL URLWithString:URLString];
    
}


#pragma mark -- 搜索好友按钮 ---
- (IBAction)searchButtonAction:(id)sender {
    if (self.textField.text.length == 0) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请先输入好友的用户名" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alertController addAction:alertAction];
        [self presentViewController:alertController animated:YES completion:nil];
        return;
    }
    [self searchNetRequest];
    self.tableView.hidden = NO;
    [self.textField resignFirstResponder];
    
}
#pragma mark --- textfield代理方法 ---
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    self.collectionView.hidden = YES;
}
// 点击return
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    self.tableView.hidden = NO;
    [self searchNetRequest];
    [self.textField resignFirstResponder];
    return YES;
}
// 点击空白
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.textField resignFirstResponder];
}
#pragma mark -- collectionView代理方法 ---
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.modelArray.count;
}
// item大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(70, 100);
}
// collectionView整体边距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, Kspace, Kspace, Kspace);
}
// 行边距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return Kspace + 10;
}
// 列边距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return Kspace * 2;
}

// item
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    AddFriendsItem *item = [collectionView dequeueReusableCellWithReuseIdentifier:@"addFriendsItem" forIndexPath:indexPath];
    RecommendFriendsModel *model = self.modelArray[indexPath.row];
    [item configureCellWithModel:model];
   
    return item;
}

// headerView
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    UICollectionReusableView *reusableView = nil;
    if ([kind isKindOfClass:[UICollectionElementKindSectionHeader class]]) {
        RecommendHeaderView *headerView = [self.collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"recommendHeaderView" forIndexPath:indexPath];
        return headerView;
    }
    return reusableView;
}
// headerView大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(KWIDTH, 40);
}
#pragma mark --- tableView代理方法 --
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.searchedFriendsArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyFriendsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myFriendsCell" forIndexPath:indexPath];
    SearchFriendsModel *model = self.searchedFriendsArray[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell configureCellWithSearchModel:model];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    // 跳转到个人信息界面
    PersonInfoViewController *personInfoVc = [[PersonInfoViewController alloc] initWithNibName:@"PersonInfoViewController" bundle:nil];
    SearchFriendsModel *model = self.searchedFriendsArray[indexPath.row];
    personInfoVc.uid = model.uid;
    [self.navigationController pushViewController:personInfoVc animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
